import 'dotenv/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, ValidationPipe } from '@nestjs/common';
import * as session from 'express-session';
import * as cookieParser from 'cookie-parser';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AuthGuard } from './guard/auth.guard';
import { LoggingInterceptor } from './interceptors/logging.interceptor';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { SECRET, PORT, PREFIX } from './config/constants';
import { RedisUtilsService } from './modules/redis-utils/redis-utils.service';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';


async function bootstrap() {
  const [app] = await Promise.all([NestFactory.create<NestExpressApplication>(AppModule)]);
  // 给请求添加prefix
  app.setGlobalPrefix(PREFIX);
  console.log('process.env',process.env);
  // 配置api文档信息
  const options = new DocumentBuilder()
    .setTitle('nest framework  api文档')
    .setDescription('nest framework  api接口文档')
    .setBasePath(PREFIX) // 设置基础的路径
    .addBearerAuth({ type: 'apiKey', in: 'header', name: 'token' }) // 设置请求头的token字段
    .setVersion('0.0.1')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup(`${PREFIX}/docs`, app, document);

  app.use(cookieParser(SECRET));
  app.use(session({ secret: SECRET, cookie: { maxAge: 60000 } }))
  // app.use(AuthMiddleware());
  const reflector = app.get<RedisUtilsService>(RedisUtilsService);
  app.useGlobalGuards(new AuthGuard(reflector))
  app.useGlobalInterceptors(new LoggingInterceptor())
  app.useGlobalInterceptors(new TransformInterceptor())
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter())

  // 配置静态文件的目录
  //方式一是直接访问:localhost:4000/1.jpg
  //app.useStaticAssets(join(__dirname, '..', 'public'));
  //方式二是访问:localhost:4000/static/1.jpg但是在public文件夹下不需要创建static目录
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/static/'
  });
  // 配置视图文件的目录
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('ejs');
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(PORT);
  Logger.log(`服务已经启动:localhost:${PORT}/${PREFIX}`);
}
bootstrap();
